import React, { PureComponent, Fragment, Component } from 'react';
import { connect } from 'dva';
import {
  Row, Col, Card, Form, Input, Radio, Select, Icon, Button, Upload, List, Modal, message, Badge, TreeSelect, Tag, InputNumber, Spin,
} from 'antd';

import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import styles from './Recomm.less';
import LayoutTypeModal from 'components/Content/LayoutTypeModal';

import { routerRedux } from 'dva/router';
import Layout from 'components/Content/Layout';

import LayoutDetail1 from './LayoutDetail1';
import LayoutDetail2 from './LayoutDetail2';
import LayoutDetail3 from './LayoutDetail3';

const FormItem = Form.Item;

@connect(({ padRecomm, loading }) => ({
  padRecomm,
  channelTree: padRecomm.channelTree,
  goodsList: padRecomm.goodsList,
  loading: loading.models.padRecomm,
}))
@Form.create()
export default class PadRecommPage extends PureComponent {
  state = {
    modalVisible: false,
    record: null,
    layoutList: [],

    weight: null,
    current: null,  //当前正在添加的数组下标

    layoutType: null,
    layoutDetail: null,
  };

  componentDidMount() {
    if (this.props.match.params.recommId != 'new') {
      this.props.dispatch({
        type: 'padRecomm/fetchRecommPage',
        payload: { recommId: this.props.match.params.recommId },
        callback: (data) => this._setRecord(data)
      })
    }
    this.props.dispatch({
      type: 'padRecomm/fetchChannelTree',
      payload: {},
    });

    this._goodsSearch()
  }

  componentWillReceiveProps(nextProps) {
    console.log('???????????????????????????', nextProps.layoutList)
  }

  _goodsSearch(filedValue) {
    this.props.dispatch({
      type: 'padRecomm/fetchGoodsList',
      payload: filedValue,
    });
  }

  _search() {
    this.props.dispatch({
      type: 'padRecomm/fetchRecommPage',
      payload: { recommId: this.props.match.params.recommId },
      callback: (data) => this._setRecord(data)
    })
  }



  _setRecord(data) {
    console.log('设置-----------------', data.layoutList)
    this.setState({ record: data, layoutList: data.layoutList, layoutDetail: null })
  }

  _addFristLayout() {
    this.setState({ weight: 1000, current: 0 })
    this._setModalVisible(true)
  }

  _addLayout(item, i) {
    let { record } = this.state;
    let weight = null;

    if ((i + 1) == record.layoutList.length) {  //点击最后一项的添加布局
      weight = item.weight + 1000;
    } else if ((i + 1) < (record.layoutList.length)) {  //点击中间的
      weight = parseInt((item.weight + record.layoutList[i+1].weight) / 2)
    }

    console.log('要添加的权重', weight)

    this.setState({ weight: weight, current: i + 1 })

    this._setModalVisible(true)
  }

  _setModalVisible(flag) {
    this.setState({ modalVisible: flag })
  }

  _chooseType(type) {
    this.props.dispatch({
      type: 'padRecomm/addRecommPageLayout',
      payload: { recommId: this.props.match.params.recommId, layoutStyle: type, weight: this.state.weight },
      callback: () => this._addLayoutBack()
    })
  }

  _addLayoutBack() {
    this.setState({
      modalVisible: false,
      weight: null,
      current: null,
    })
    this._search()
  }

  _deleteLayout(item, i) {
    this.props.dispatch({
      type: 'padRecomm/deletePageLayout',
      payload: { layoutId: item.layoutId },
      callback: () => this._search()
    })
  }

  _editLayout(item, i) {
    console.log('布局详情', item);
    this.setState({ layoutDetail: item })
  }

  swapArray(arr, index1, index2) {
    arr[index1] = arr.splice(index2, 1, arr[index1])[0];
    return arr;
  }

  _forwardLayout(oldList, item, i) {
    console.log('iiiiiiiiiiiiiii', i)
    if (i == 0) return;
    let record = this.state.record;
    // let oldList = this.state.layoutList;
    console.log('老的数组》》》》》》》》》', oldList)

    let before = oldList[(i - 1)];
    let click = oldList[i];

    let newList = [];
    for (let j = 0; j < oldList.length; j++) {
      if (j == (i - 1)) {
        newList.push(click)
      } else if (j == i) {
        newList.push(before)
      } else {
        newList.push(oldList[j])
      }
    }

    if (newList && (newList.length > 0)) {
      let list = [];
      for (let k = 0; k < newList.length; k++) {
        let one = newList[k];
        one.weight = (k + 1) * 1000;
        list.push(one)
      }
      newList = list;
    }
    record.layoutList = newList;
    this.setState({ record: record, layoutList: newList })
  }

  _backLayout(oldList, item, i) {
    console.log('iiiiiiiiiiiiiii', i)
    if (i == oldList.length) return;
    let record = this.state.record;
    // let oldList = this.state.layoutList;
    console.log('老的数组》》》》》》》》》', oldList)

    let after = oldList[(i + 1)];
    let click = oldList[i];

    let newList = [];
    for (let j = 0; j < oldList.length; j++) {
      if (j == (i)) {
        newList.push(after)
      } else if (j == (i + 1)) {
        newList.push(click)
      } else {
        newList.push(oldList[j])
      }
    }
    if (newList && (newList.length > 0)) {
      let list = [];
      for (let k = 0; k < newList.length; k++) {
        let one = newList[k];
        one.weight = (k + 1) * 1000;
        list.push(one)
      }
      newList = list;
    }
    record.layoutList = newList;
    this.setState({ record: record, layoutList: newList })
    
  }

  _savePage() {
    console.log('最终保存数据', this.state.record)
    this.props.form.validateFields((err, fieldsValue) => {
      if (err) return;
      let values = {};
      values['recommId'] = this.state.record.recommInfo.recommId;
      values['appType'] = this.state.record.recommInfo.appType;
      values['recommName'] = fieldsValue.recommName;

      let list = []
      if (this.state.layoutList && (this.state.layoutList.length > 0)) {
        for (let i = 0; i < this.state.layoutList.length; i++) {
          let one = this.state.layoutList[i];
          let newOne = {};
          newOne['layoutStyle'] = one.layoutStyle;
          newOne['layoutId'] = one.layoutId;
          newOne['weight'] = (i + 1) * 1000;
          list.push(newOne)
        }
      }

      values['layoutList'] = list;

      this.props.dispatch({
        type: 'padRecomm/editPageLayout',
        payload: values,
        callback: () => this._search()
      })
    })
  }


  render() {
    const { record, layoutList, layoutDetail } = this.state;
    const { form } = this.props;
    return (
      <PageHeaderLayout>
        <div className={styles.container}>
          <div className={styles.header}>
            iPad
          </div>

          <div >
            <div className={styles.layoutContainer}>
              {(record && layoutList && (layoutList.length > 0)) ?
                layoutList.map((item, i) =>
                  <Layout item={item} key={item.layoutId} first={layoutList[0].weight} last={layoutList[layoutList.length - 1].weight}
                    editLayout={() => this._editLayout(item, i)}
                    forwardLayout={() => this._forwardLayout(layoutList, item, i)}
                    backLayout={() => this._backLayout(layoutList, item, i)}
                    addLayout={() => this._addLayout(item, i)}
                    deleteLayout={() => this._deleteLayout(item, i)}
                  />)
                :
                <div style={{ flex: 1, display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
                  <Button type="primary" onClick={() => this._addFristLayout()} >添加布局</Button>
                </div>
              }
            </div>
            <div style={{ width: '30%', marginTop: '15px' }}>
              <FormItem labelCol={{ span: 6 }} wrapperCol={{ span: 18 }} label="页面名称" >
                {form.getFieldDecorator('recommName', {
                  initialValue: (record && record.recommInfo && record.recommInfo.recommName) ? record.recommInfo.recommName : null,
                  rules: [{ required: true, message: '请输入页面名称' }],
                })(<Input placeholder="请输入页面名称" maxLength="10" />)}
              </FormItem>
              <FormItem>
                <Button type="primary" onClick={() => this._savePage()}>保存</Button>
                <Button type="primary" style={{ marginLeft: '30px' }} onClick={() => { this.props.dispatch(routerRedux.goBack()) }}>返回列表</Button>
              </FormItem>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', justifyContent: "center", alignItems: 'center' }}>
              {layoutDetail ?
                ((layoutDetail.layoutStyle == '0') || (layoutDetail.layoutStyle == '2') ) ?
                  <div className={styles.editItem}>
                    <LayoutDetail1 layoutDetail={layoutDetail}
                      channelTree={this.props.channelTree} goodsList={this.props.goodsList}
                      goodsSearch={(filedValue) => this._goodsSearch(filedValue)}
                      recommPageSearch={() => this._search()}
                    />
                  </div>
                  :
                  ((layoutDetail.layoutStyle == '1') || (layoutDetail.layoutStyle == '3')) ?
                    <div className={styles.editItem2}>
                      <LayoutDetail2 layoutDetail={layoutDetail}
                        channelTree={this.props.channelTree} goodsList={this.props.goodsList}
                        goodsSearch={(filedValue) => this._goodsSearch(filedValue)}
                        recommPageSearch={() => this._search()}
                      />
                    </div>
                    :
                    ((layoutDetail.layoutStyle == '4') || (layoutDetail.layoutStyle == '5')) ?
                      <div className={styles.editItem3}>
                        <LayoutDetail3 layoutDetail={layoutDetail}
                          channelTree={this.props.channelTree} goodsList={this.props.goodsList}
                          goodsSearch={(filedValue) => this._goodsSearch(filedValue)}
                          recommPageSearch={() => this._search()}
                        />
                      </div>
                      :
                      null
                :
                null
              }
              <div style={{ height: '100px' }}></div>
            </div>
          </div>

          <LayoutTypeModal visible={this.state.modalVisible} chooseType={(type) => this._chooseType(type)}
            cancel={() => this._setModalVisible(false)}
          />


        </div>
      </PageHeaderLayout>
    )
  }
}